package ecnu.ecgbackend.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ecnu.ecgbackend.config.redis.RedisService;
import ecnu.ecgbackend.dao.UserMapper;
import ecnu.ecgbackend.entity.User;
import ecnu.ecgbackend.service.DiagnosisCommonService;
import ecnu.ecgbackend.utils.Result;
import ecnu.ecgbackend.utils.SmsSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class DiagnosisCommonServiceImpl implements DiagnosisCommonService {
    @Resource
    UserMapper userMapper;
    @Resource
    RedisService redisService;
    @Override
    public Result sendCode(String phone) {
        List<String> phones=userMapper.selectList(new QueryWrapper<User>()).stream().map(User::getPhone).collect(Collectors.toList());
        if(phones.contains(phone)){
            return Result.error().message("该手机号已被使用");
        }
        Random randObj = new Random();
        String code= Integer.toString(100000 + randObj.nextInt(900000));
        SendSmsResponse response = SmsSender.sendSms(phone,"心电图辅助诊断系统","SMS_464740617","{\"code\":\""+code+"\"}");
        redisService.set(phone,code,600L);
        if(response!=null){
            return Result.ok().message("验证码发送成功！");
        }else {
            return Result.error().message("验证码发送失败");
        }
    }

    @Override
    public Result sendVerifyCode(String username, String phone) {
        User user=userMapper.selectOne(new QueryWrapper<User>().eq("username",username));
        if(user==null){
            return Result.error().message("该用户不存在");
        }
        String _phone=user.getPhone();
        if(!phone.equalsIgnoreCase(_phone)){
            return Result.error().message("该手机号非注册手机号");
        }
        Random randObj=new Random();
        String code=Integer.toString(100000+randObj.nextInt(900000));
        SendSmsResponse response = SmsSender.sendSms(phone,"心电图辅助诊断系统","SMS_464740617","{\"code\":\""+code+"\"}");
        redisService.set(phone,code,600L);
        return Result.ok().message("验证码发送成功！");
    }

    @Override
    public Result verify(String phone, String code) {
        String _code=redisService.get(phone);
        System.out.println("_code: "+code);
        if(_code==null){
            return Result.error().message("验证码已失效");
        }
        if(!code.equalsIgnoreCase(_code)){
            return Result.error().message("验证码错误");
        }
        return Result.ok().message("验证成功！");
    }

}
